package com.sskj.gocoinapp.ui.fragment;


import android.animation.Animator;
import android.animation.ValueAnimator;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.base.App;
import com.sskj.common.box.imageloader.GlideImageLoader;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.LanguageUtil;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.utils.SPUtils;
import com.sskj.gocoinapp.R;
import com.sskj.gocoinapp.bean.BannerBean;
import com.sskj.gocoinapp.bean.GuideListBean;
import com.sskj.gocoinapp.component.DaggerUserDataComponent;
import com.sskj.gocoinapp.http.HttpConfig;
import com.sskj.gocoinapp.presenter.HangqingFragmentPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.ColorEnum;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.youth.banner.Banner;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.APP_HANGQING)
public class HangqingFragment extends BaseFragment<HangqingFragmentPresenter> {

    @BindView(R.id.banner)
    Banner banner;

    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R.id.tvCoinTypeFirst)
    TextView tvCoinTypeFirst;
    @BindView(R.id.tvCoinUSDTFirst)
    TextView tvCoinUSDTFirst;
    @BindView(R.id.tvCoinRateFirst)
    TextView tvCoinRateFirst;
    @BindView(R.id.tvCoinCNYFirst)
    TextView tvCoinCNYFirst;
    @BindView(R.id.tvCoinTypeSecond)
    TextView tvCoinTypeSecond;
    @BindView(R.id.tvCoinUSDTSecond)
    TextView tvCoinUSDTSecond;
    @BindView(R.id.tvCoinRateSecond)
    TextView tvCoinRateSecond;
    @BindView(R.id.tvCoinCNYSecond)
    TextView tvCoinCNYSecond;
    @BindView(R.id.tvCoinTypeThird)
    TextView tvCoinTypeThird;
    @BindView(R.id.tvCoinUSDTThird)
    TextView tvCoinUSDTThird;
    @BindView(R.id.tvCoinRateThird)
    TextView tvCoinRateThird;
    @BindView(R.id.tvCoinCNYThird)
    TextView tvCoinCNYThird;
    @BindView(R.id.day_day_dig_mine)
    LinearLayout dayDayDigMine;
    @BindView(R.id.viewDig)
    View viewDig;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R.id.tvMore)
    TextView tvMore;
    private Disposable noticeDispo;
    private GuideListBean noticeList;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private ValueAnimator valueAnimator;
    private ValueAnimator valueAnimator1;
    private ValueAnimator valueAnimator2;
    private Disposable firstDispo;
    private Disposable secondDispo;
    private Disposable thirdDispo;


    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_hangqing;
    }

    @Override
    public HangqingFragmentPresenter getPresenter() {
        return new HangqingFragmentPresenter();
    }

    @Override
    public void initView() {
       LanguageUtil.changeAppLanguage(getActivity(), LanguageUtil.getAppLocale(App.INSTANCE), true);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.getData();
            }
        });
        ClickUtil.click(tvMore, () -> {
            ARouter.getInstance().build(RConfig.APP_GONGGAO_LIST).navigation();
        });
        ClickUtil.click(dayDayDigMine, () -> {
            if (userData == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                return;
            }
            ARouter.getInstance().build(RConfig.APP_MINING).navigation();
        });
        if (!LanguageUtil.isChinese()){
            viewDig.setBackgroundResource(R.mipmap.app_bg_dig_en);
        }
//        boolean equals = ((String) SPUtils.get(com.sskj.gocoin.common.App.INSTANCE, Constants.LANGUAGE, "zh", "zh")).equals("zh");
//        if (!equals){
//            viewDig.setBackgroundResource(R.mipmap.app_bg_dig_en);
//        }
        banner.setImageLoader(new GlideImageLoader());
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_8e9));
            return textView;
        });
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayout, (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_COIN_LIST).navigation())
                .commitAllowingStateLoss();
    }

    @Override
    public void initData() {

        mPresenter.getData();
        mPresenter.getBanner();
        mPresenter.getNotice();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(CoinBean data) {
        if (tvCoinCNYFirst == null || data == null)
            return;
        Flowable.fromArray(data)
                .filter(coinBean -> {
                    if (coinBean.getCode().toUpperCase().equals("BTC_USDT")) {
                        tvCoinUSDTFirst.setText(coinBean.getPrice());
                        tvCoinCNYFirst.setText(String.format("≈%s CNY", coinBean.getCnyPrice()));
                        tvCoinRateFirst.setText(coinBean.getChangeRate());
                        tvCoinUSDTFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        tvCoinRateFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        DisposUtil.close(firstDispo);
                        firstDispo = Flowable.timer(1, TimeUnit.SECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aLong -> {
                                    if (tvCoinUSDTFirst == null)
                                        return;
                                    tvCoinUSDTFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.commonWhite));
                                });
                        return false;
                    }
                    return true;
                })
                .filter(coinBean -> {
                    if (coinBean.getCode().toUpperCase().equals("ETH_USDT")) {
                        tvCoinUSDTSecond.setText(coinBean.getPrice());
                        tvCoinCNYSecond.setText(String.format("≈%s CNY", coinBean.getCnyPrice()));
                        tvCoinRateSecond.setText(coinBean.getChangeRate());
                        tvCoinUSDTSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        tvCoinRateSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        DisposUtil.close(secondDispo);
                        secondDispo = Flowable.timer(1, TimeUnit.SECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aLong -> {
                                    if (tvCoinUSDTSecond == null)
                                        return;
                                    tvCoinUSDTSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.commonWhite));
                                });
                        return false;
                    }
                    return true;
                })
                .filter(coinBean -> {
                    if (coinBean.getCode().toUpperCase().equals("BCH_USDT")) {
                        tvCoinUSDTThird.setText(coinBean.getPrice());
                        tvCoinCNYThird.setText(String.format("≈%s CNY", coinBean.getCnyPrice()));
                        tvCoinRateThird.setText(coinBean.getChangeRate());
                        tvCoinUSDTThird.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        tvCoinRateThird.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        DisposUtil.close(thirdDispo);
                        thirdDispo = Flowable.timer(1, TimeUnit.SECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aLong -> {
                                    if (tvCoinUSDTThird == null)
                                        return;
                                    tvCoinUSDTThird.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.commonWhite));
                                });

                        return false;
                    }
                    return true;
                }).subscribe();

        ;
    }

    public void updateUI(List<CoinBean> data) {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
        if (data == null||tvCoinCNYFirst==null) {
            return;
        }
        RxBus.getDefault().post(data);
        Flowable.fromIterable(data)
                .filter(coinBean -> {
                    if (coinBean.getCode().toUpperCase().equals("BTC_USDT")) {
                        tvCoinUSDTFirst.setText(coinBean.getPrice());
                        tvCoinCNYFirst.setText(String.format("≈%s CNY", coinBean.getCnyPrice()));
                        tvCoinRateFirst.setText(coinBean.getChangeRate());
//                        tvCoinUSDTFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
//                        tvCoinRateFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        return false;
                    }
                    return true;
                })
                .filter(coinBean -> {
                    if (coinBean.getCode().toUpperCase().equals("ETH_USDT")) {
                        tvCoinUSDTSecond.setText(coinBean.getPrice());
                        tvCoinCNYSecond.setText(String.format("≈%s CNY", coinBean.getCnyPrice()));
                        tvCoinRateSecond.setText(coinBean.getChangeRate());
//                        tvCoinUSDTSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
//                        tvCoinRateSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        return false;
                    }
                    return true;
                })
                .filter(coinBean -> {
                    if (coinBean.getCode().toUpperCase().equals("BCH_USDT")) {
                        tvCoinUSDTThird.setText(coinBean.getPrice());
                        tvCoinCNYThird.setText(String.format("≈%s CNY", coinBean.getCnyPrice()));
                        tvCoinRateThird.setText(coinBean.getChangeRate());
//                        tvCoinUSDTThird.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
//                        tvCoinRateThird.setTextColor(ContextCompat.getColor(App.INSTANCE, coinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
                        return false;
                    }
                    return true;
                }).subscribe();

    }

    public void updateBanner(List<BannerBean> data) {
        if (banner == null)
            return;
        Flowable.fromIterable(data)
                .map(bannerBean -> HttpConfig.BASE_URL + bannerBean.getPath())
                .toList()
                .subscribe(strings -> {
                    banner.setImages(strings);
                    banner.setOnBannerListener(position -> {
//                        ARouter.getInstance().build(RConfig.APP_GUIDE_WEB)
//                                .withString(Constans.URL, data.get(position).getUrl())
//                                .navigation();
                    });
                    banner.start();
                });
    }


    @Override
    public void onDestroy() {
        DisposUtil.close(noticeDispo);
        DisposUtil.close(firstDispo);
        DisposUtil.close(secondDispo);
        DisposUtil.close(thirdDispo);
        super.onDestroy();
    }

    public void finishRefresh() {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
    }

    public void updateNotice(List<GuideListBean> notice) {
        if (tvNotice != null) {
            if (notice.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeList = notice.get((int) (i % notice.size()));
                                tvNotice.setText(noticeList.getTitle());
                                ClickUtil.click(tvNotice, () -> {
                                    ARouter.getInstance()
                                            .build(RConfig.APP_GUIDE_WEB)
                                            .withString(Constans.HEAD, App.INSTANCE.getString(R.string.appJavaGuideListFragment8))
                                            .withString(Constans.ID, noticeList.getId())
                                            .withString(Constans.TIME, noticeList.getCreate_time())
                                            .withString(Constans.TITLE, noticeList.getTitle())
                                            .navigation();
                                });
                            }
                        }, System.out::println);
            }
        }
    }
}
